import { computed } from "vue";
import Taro, { navigateBack } from "@tarojs/taro";
import { useTzRouter } from "@/vhooks/useTzRouter";
import { getUserInfo } from "@/utils/storage";
import { saveReceiveMan } from "./useReceiveForm";
import {
  saveOrUpdateApi,
  applyApi,
  templateIdList,
  getFeeAgreeVOByCustRegNoApi,
  saveValidateApi,
} from "./api";

export const useHandleBtn = ({ state, isValidate }) => {
  const { redirectTo } = useTzRouter();
  const { userType } = getUserInfo();

  const validateSubmitParams = (params) => {
    return new Promise((resolve, reject) => {
      saveValidateApi(params)
        .then((res) => {
          resolve(true);
        })
        .catch((err) => {
          resolve(
            Taro.showModal({
              content: err.data.msg?.replace(/<\/br>/g, "\r\n"),
              confirmText: "确定",
              cancelText: "取消",
            })
          );
        });
    });
  };
  /**
   * 提交数据
   * @param {*} toApply 为 1 标识跳转到申报详情页
   */
  const handleSubmit = async (toApply) => {
    if (isValidate()) {
      state.handleBtnDisabled = true;
      let params = state.detailData || {};
      params = {
        ...params,
        ...state.baseForm,
        ...state.receiveForm,
        itemList: state.goodsForms,
      };
      // 转运信息
      if (state.transhipmentInfo) {
        params.transhipmentInfo = { ...state.transhipmentInfo };
      }

      if (state.ccrnId) {
        params.id = state.ccrnId;
      }

      try {
        // 获取金额数据
        const feeData = await getFeeAgreeVOByCustRegNoApi();
        // balance 账户余额  combined 费目金额
        const { balance, combined } = feeData.data;
        // 增加费用信息
        state.feeInfo = {
          balance,
          combined,
        };
      } catch (err) {
        console.log("获取金额数据失败：", err);
      }

      try {
        // 校验数据
        const validateRes = await validateSubmitParams(params);
        if (validateRes.cancel) {
          // 取消
          state.handleBtnDisabled = false;
          return;
        }
        // 保存
        Taro.showLoading({
          title: "加载中",
        });
        const saveResData = await saveOrUpdateApi(params);
        $TzNotify.success(toApply ? "提交成功" : "暂存成功");
        // 缓存接口获取的数据
        state.detailData = saveResData.data;
        state.ccrnId = saveResData.data.id;
        if (toApply) {
          // 切换到 申报模式
          state.underApply = true;
          // 禁用输入
          state.formsDisabled = true;
          // 展示转运信息
          state.showTransportForm = true;
        }
      } catch (err) {
        $TzNotify.danger(err.data?.msg || toApply ? "提交失败" : "暂存失败");
      }
      Taro.hideLoading();
      state.handleBtnDisabled = false;
    }
  };
  // 申报
  const handleApply = async () => {
    state.handleBtnDisabled = true;
    console.log(state);

    try {
      // 判断是否余额不足
      // const feeData = await getFeeAgreeVOByCustRegNoApi();
      // // balance 账户余额  combined 费目金额
      const { balance, combined } = state.feeInfo;
      if (
        userType.isPersonal &&
        balance !== null &&
        combined !== null &&
        (+balance <= 0 || +balance < +combined)
      ) {
        Taro.showModal({
          content: "账户余额不足,立即充值!",
          confirmText: "确定",
          cancelText: "取消",
        }).then((res) => {
          if (res.cancel) {
            Taro.hideLoading();
            state.handleBtnDisabled = false;
            return;
          }
          redirectTo({
            path: "/pages/subUser/recharge/index",
          });
        });
        return;
      }
      Taro.showLoading({
        title: "加载中",
      });
      // 提交申报
      // await applyApi(state.applyId);
      await applyApi(state.ccrnId);

      $TzNotify.success("提交申报成功");

      Taro.hideLoading();

      // 发起订阅消息的授权
      Taro.requestSubscribeMessage({
        // tmplIds: templateIdList,
        tmplIds: ["TxOurbMPm3Bwz-y9CkwqSLGoXCt7CBRqJte2Ot4d5Ag"],
        complete(res) {
          console.log(res);
        },
      });
      await Taro.showModal({
        content:
          "请等待30秒~2分钟，通过微信查看推送提醒，或进入【无缝查询】实时查看单据状态。",
        confirmText: "好",
        showCancel: false,
      });
      // 跳转到 ccrn查询列表页
      redirectTo({
        path: "/pages/subHK/ccrnInquire/home/index",
      });
      state.handleBtnDisabled = false;
    } catch (err) {
      console.log(err);
      $TzNotify.danger(err.data.msg || "提交申报失败");
      Taro.hideLoading();
      state.handleBtnDisabled = false;
    }
  };

  const btnDom = computed(() => {
    if (state.underApply) {
      // 申报确认页面的按钮
      return (
        <tz-view class="btn-wrap">
          <tz-button
            disabled={state.handleBtnDisabled}
            type="primary"
            onClick={handleApply}
          >
            确认申报
          </tz-button>
          <tz-button
            disabled={state.handleBtnDisabled}
            type="default"
            onClick={() => {
              state.underApply = false;
              state.formsDisabled = false;
              state.showTransportForm = false;
            }}
          >
            返回编辑
          </tz-button>
        </tz-view>
      );
    } else if (state.ccrnId) {
      // 详情草稿的按钮
      return (
        <>
          <tz-view class="btn-wrap abreast">
            <tz-button
              disabled={state.handleBtnDisabled}
              type="primary"
              onClick={() => handleSubmit()}
            >
              暂存
            </tz-button>
            <tz-button
              disabled={state.handleBtnDisabled}
              type="primary"
              onClick={() => handleSubmit(1)}
            >
              提交申报
            </tz-button>
          </tz-view>
          <tz-button
            disabled={state.handleBtnDisabled}
            type="default"
            onClick={() => navigateBack({ delta: 1 })}
          >
            返回
          </tz-button>
        </>
      );
    } else {
      // TODO: 草稿的按钮与这里相同，暂时保留，后面考虑合并
      return (
        <>
          <tz-view class="btn-wrap abreast">
            <tz-button
              disabled={state.handleBtnDisabled}
              type="primary"
              onClick={() => handleSubmit()}
            >
              暂存
            </tz-button>
            <tz-button
              disabled={state.handleBtnDisabled}
              type="primary"
              onClick={() => handleSubmit(1)}
            >
              提交申报
            </tz-button>
          </tz-view>
          <tz-button
            disabled={state.handleBtnDisabled}
            type="default"
            onClick={() => navigateBack({ delta: 1 })}
          >
            返回
          </tz-button>
        </>
      );
    }
  });

  return <tz-view class="btn-area">{btnDom.value}</tz-view>;
};
